﻿using ProjectManager.Logic.Content;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManager.Logic
{
    internal static class Sorter
    {
        public static List<TeamInformation> TeamSort(this List<TeamInformation> teams
            , MemberInformation CurrentIdentity)
        {
            List<TeamInformation>? selfTeam = [];
            List<TeamInformation> selfMajorTeams = [];
            List<TeamInformation> selfJoinedTeams = [];
            List<TeamInformation> otherTeams = [];

            foreach (TeamInformation team in teams)
            {
                if (team.IsCancelled)
                {
                    continue;
                }
                if (team.Leader.Equals(CurrentIdentity))
                {
                    if (team.IsIndividual)
                        selfTeam.Add(team);
                    else
                        selfMajorTeams.Add(team);
                    continue;
                }
                bool joined = false;
                foreach (TeamInformation childTeam in team.Members)
                {
                    if ((!childTeam.IsCancelled) && childTeam.Leader.Equals(CurrentIdentity))
                    {
                        selfJoinedTeams.Add(team);
                        joined = true;
                        break;
                    }
                }
                if (!joined)
                {
                    otherTeams.Add(team);
                }
            }
            if (selfTeam.Count != 1)
                throw new Exception("找不到自己个人团队");
            List<TeamInformation> result = [];
            result.AddRange(selfTeam);
            result.AddRange(selfMajorTeams);
            result.AddRange(selfJoinedTeams);
            result.AddRange(otherTeams);
            return result;
        }
    }
}
